#!/usr/bin/env zx

// cd("/Volumes/Data/repos/test/pnpm-mono");
// const output =
//   await $`git rev-parse --abbrev-ref --symbolic-full-name @{u}`.nothrow();
// console.log(output);
// if (!output.stderr) {
//   const tracking = output2lines(output);
//   console.log(tracking);
// }

/////////////////////////////////////////////////////////////////////////////////////////////////////

const folders = argv._.length ? argv._ : ["."];

fetchAll(folders);

async function fetchAll(folders) {
  for (let i = 0; i < folders.length; i++) {
    const folder = folders[i];
    await fetchInFolder(folder);
  }
}

async function fetchInFolder(folder) {
  within(async () => {
    await cd(folder);
    const reposOutput = await $`find . -type d -name .git`;

    const repos = output2lines(reposOutput);

    for (let i = 0; i < repos.length; i++) {
      const repo = repos[i];
      const repoResult = await within(async () => {
        const pwd = path.resolve(repo + "/..");
        await cd(pwd);

        const output2 =
          await $`git rev-parse --abbrev-ref --symbolic-full-name @{u}`
            .quiet()
            .nothrow();
        if (output2.stderr) {
          return output2.stderr;
        }
        await $`git fetch --all`.quiet();
        const tracking = output2lines(output2);
        if (tracking.length) {
          const result = await $`git pull`.quiet();
          return result.stdout;
        }
        return `There is no tracking information for the current branch.`;
      });
      console.log(repoResult);
    }
  });
}

function output2lines(output) {
  const str = output.stdout.trim();
  return str ? str.split("\n").map((line) => line.trim()) : [];
}
